package com.starry.chat.logic.network

import androidx.lifecycle.liveData
import com.google.gson.Gson
import com.starry.chat.logic.model.ChatBodyBean
import com.starry.core.constant.GlobalConfig
import com.starry.core.utils.GsonUtils
import kotlinx.coroutines.Dispatchers
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.ResponseBody

/**
 * Package:com.starry.chat.logic.network
 * Author:starr
 * Time:2024/4/6 16:22
 * Description:
 */
object Repository {

    fun getBaiduToken() = liveData(Dispatchers.IO){
        val result = try {
            val response = AppNetWork.getBaiduToken(
                GlobalConfig.client_KEY, GlobalConfig.SECRET_KEY,
                "client_credentials")
            if (response?.accessToken!= null) {
                Result.success(response)
            } else {
                Result.failure(RuntimeException("error"))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
        emit(result)
    }

    fun startChat(param: ChatBodyBean, accessToken: String) = liveData(Dispatchers.IO){
        val result = try {
            //将参数实体转换为RequestBody
            val mediaType: MediaType? = "application/json".toMediaTypeOrNull()
            //noinspection deprecation
            val body: RequestBody = RequestBody.create(mediaType, GsonUtils.getGsonInstance().toJson(param))
            val response = AppNetWork.startChat(body, accessToken)
            if (response?.result != null) {
                Result.success(response)
            } else {
                Result.failure(RuntimeException("error"))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
        emit(result)
    }
}